/*
 * Copyright (c) 2011. This file is public under GPLv3 license.
 * For more information about license please refer to http://www.gnu.org/licenses/gpl.html
 */

package com.freetools.watchdog.engine;

import com.freetools.watchdog.commands.*;
import com.freetools.watchdog.exceptions.CommandErrorException;
import com.freetools.watchdog.exceptions.ParametersErrorException;
import com.freetools.watchdog.model.ICommand;
import com.freetools.watchdog.model.IModelHolder;
import org.apache.log4j.Logger;

/**
 * @author Michael Morozov
 */
public class CommandFlow
{
    private static final Logger log = Logger.getLogger(CommandFlow.class);

    private static ICommand checkModelOnExistCommand(IModelHolder model, Class<? extends ICommand> clazz)
    {
        for (ICommand iCommand : model.getCommands())
        {
            if (clazz.equals(iCommand.getClass()))
                return iCommand;
        }
        return null;
    }

    public static boolean execute(IModelHolder model)
    {
        try
        {
            ICommand command = checkModelOnExistCommand(model, DBCmd.class);
            if (command != null)
            {
                command.execute(model);
                model.getCommands().remove(command);
            }
            command = checkModelOnExistCommand(model, ColumnsCmd.class);
            if (command != null)
            {
                command.execute(model);
                model.getCommands().remove(command);
            }
            command = checkModelOnExistCommand(model, FileCmd.class);
            if (command != null)
            {
                command.execute(model);
                model.getCommands().remove(command);
            }
            command = checkModelOnExistCommand(model, ParseCmd.class);
            if (command != null)
            {
                command.execute(model);
                model.getCommands().remove(command);
            }

            for (ICommand _command : model.getCommands())
            {
                if (!(_command instanceof RunCmd))
                    _command.execute(model);
            }

            command = checkModelOnExistCommand(model, RunCmd.class);
            if (command != null)
            {
                command.execute(model);
                model.getCommands().remove(command);
            }
        } catch (ParametersErrorException e)
        {
            log.error(e);
            throw new RuntimeException(e.getMessage(), e);
            //new HelpCmd().execute(model);
        } catch (CommandErrorException e)
        {
            UserInformation.info(e.getMessage());
            log.error(e);
        }

        return checkModelOnExistCommand(model, ExitCmd.class) != null;
    }

}
